package com.wemei.auto.ui.utils

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager

class FragmentChangeManager(
    private val mFragmentManager: FragmentManager,
    private val mContainerViewId: Int,
    private val mFragments: MutableList<Fragment>,
    index: Int = 0,
    isLazy: Boolean = true,
) {
    private var mCurrentTab: Int = index

    init {
        var fragment: Fragment
        var tag: String
        for (i in mFragments.indices) {
            fragment = mFragments[i]
            tag = String.format("%s-%s", fragment.javaClass.name, i)
            val fragmentByTag = mFragmentManager.findFragmentByTag(tag)
            if (fragmentByTag != null) {
                mFragments[i] = fragmentByTag
                mFragmentManager.beginTransaction().hide(fragmentByTag).commitAllowingStateLoss()
            } else {
                if (!isLazy) {
                    mFragmentManager.beginTransaction().add(mContainerViewId, fragment, tag).hide(fragment).commitAllowingStateLoss()
                    mFragmentManager.executePendingTransactions()
                }
            }
        }
        setFragments(index)
    }

    fun setFragments(index: Int) {
        if (index == -1 || index >= mFragments.size) return
        val ft = mFragmentManager.beginTransaction()
        for (i in mFragments.indices) {
            val fragment = mFragments[i]
            val tag = String.format("%s-%s", fragment.javaClass.name, index)
            if (i == index) {
                if (!fragment.isAdded) {
                    mFragmentManager.beginTransaction().add(mContainerViewId, fragment, tag).commitAllowingStateLoss()
                    mFragmentManager.executePendingTransactions()
                } else {
                    ft.show(fragment)
                }
            } else {
                if (fragment.isAdded && !fragment.isHidden) {
                    ft.hide(fragment)
                }
            }
        }
        ft.commitAllowingStateLoss()
        mCurrentTab = index
    }
}